package hashTable;

import java.util.Iterator;

public class MyLinkedList<T> implements Iterable<T> {
    private MyLinkedNode<T> head;
    private MyLinkedNode<T> last;
    public MyLinkedList() {
        head = new MyLinkedNode<T>();
        last = null;
    }

    public void add(String id, T element){
        MyLinkedNode<T> node = new MyLinkedNode<>(id,element);
        if(last==null){
            head.setNext(node);
        }else {
            last.setNext(node);
        }
        last=node;
    }

    public int delete(String id){
        if(head.getNext()==null){
            return 0;
        }
        MyLinkedNode<T> pNode = head;
        MyLinkedNode<T> node = head.getNext();
        while(node!=null){
            if(node.getId().equals(id)){
                break;
            }
            pNode = pNode.getNext();
            node = node.getNext();
        }
        pNode.setNext(node.getNext());
        return 1;
    }

    public T search(String id){
        T element = null;
        if(head.getNext()==null){
            return null;
        }
        MyLinkedNode<T> node = head.getNext();
        while(node!=null){
            if(node.getId().equals(id)){
                element = node.getElement();
                break;
            }
            node = node.getNext();
        }
        return element;
    }

    @Override
    public Iterator<T> iterator() {
        return new MyLinkedListIterator<T>(head);
    }
}
